package com.clz.mycustomview.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

/**
 * 绘制一个矩形，当手指在这个矩形区域内，矩形变为绿色，不在这个区域，矩形变为红色
 */
public class RectPointView extends View {
    private Paint mPaint;
    private int mX,mY;
    private RectF mRectf;
    public RectPointView(Context context) {
        super(context);
        init();
    }

    public RectPointView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public RectPointView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    private void init(){
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(8);
        mPaint.setColor(Color.RED);
        mRectf = new RectF(50,80,400,280);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mRectf.contains(mX,mY)){
            mPaint.setColor(Color.GREEN);
        }else {
            mPaint.setColor(Color.RED);
        }
        canvas.drawRect(mRectf,mPaint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mX = (int) event.getX();
        mY = (int) event.getY();
        Log.i("MOVE",mX+ ":" + mY);
        if (event.getAction() == MotionEvent.ACTION_DOWN){
            invalidate();
            // true 表示该控件要消费用户的触摸事件
            return true;
        }else {
            mX = -1;
            mY = -1;
        }
        postInvalidate();
        return super.onTouchEvent(event);
    }
}
